package com.chinawlx.wlxteacher.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.chinawlx.wheelview.OptionsPickerView;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXWheelViewUtils;
import com.chinawlx.wlxteacher.widget.WLXChooseLessonView;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.widget.radiogroup.WLXFlowRadioGroup;
import com.chinawlx.wlxteacher.wlx_schedule;
import com.chinawlx.wlxteacher.wlx_scheduleDao;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * 作者:黄帅
 * 时间:16/9/10
 * 描述:班级调课界面
 */
public class WLXClazzAdjustActivity extends WLXBaseActivity {
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_save)
    TextView mTvSave;
    @BindView(R.id.tv_clazz_name)
    TextView mTvClazzName;
    @BindView(R.id.iv_adjust)
    ImageView mIvAdjust;
    @BindView(R.id.tv_adjust_time)
    TextView mTvAdjustTime;
    @BindView(R.id.choose_adjust_lesson)
    WLXChooseLessonView mChooseAdjustLesson;
    @BindView(R.id.choose_adjust_lesson_to)
    WLXChooseLessonView mChooseAdjustLessonTo;
    @BindView(R.id.tv_center_adjust_line)
    TextView mTvCenterAdjustLine;
    @BindView(R.id.flowRadioGroup)
    WLXFlowRadioGroup mFlowRadioGroup;

    private RadioButton[] radioButtons;
    private String[] titles = {"学习考试", "身体不适", "家中急事", "假日休息", "婚假产假"};
    private String[] reason_codes = {"study", "health", "housework", "holiday", "marriage"};
    private String reasonCode;
    private String schedule_id;//课次ID
    private String new_start_date;//新的开始时间
    private String new_end_date;//新的结束时间
    private List<wlx_schedule> mWlx_schedules;
    private ArrayList<String> adjustTimes = new ArrayList<>();
    private Long lowTime = -1L;//最低的时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adjust_lesson);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initRadioButton();
        loadDataFromDb();
        initView();
    }

    //从数据库拿数据
    private void loadDataFromDb() {
        //拿到课程数据,比当前时间大的才显示
        mWlx_schedules = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
                (wlx_scheduleDao.Properties.Grade_id
                                .eq(WLXConstant.GRADE_ID), wlx_scheduleDao.Properties
                                .Teacher_user_id.eq
                                        (WLXConstant.USER_ID)
                        , wlx_scheduleDao.Properties.Opening_date.gt(System.currentTimeMillis() /
                                1000)
                ).orderAsc(wlx_scheduleDao.Properties
                .Opening_date)
                .list();

        adjustTimes.clear();
        for (wlx_schedule bean : mWlx_schedules) {
            //开始时间,结束时间
            String startTime = WLXDateUtil.getDateToString(bean.getOpening_date(), "MM月dd日 HH:mm");
            String endTime = WLXDateUtil.getDateToString(bean.getClosing_date(), "HH:mm");
            adjustTimes.add(startTime + "-" + endTime);

            if (lowTime == -1) {
                lowTime = bean.getOpening_date();
            }
        }
    }

    private void initView() {
        mTvClazzName.setText(WLXConstant.GRADE_TITLE);
        mFlowRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < radioButtons.length; i++) {
                    if (radioButtons[i].getId() == checkedId) {
                        //得到选中的文字对应编码
                        reasonCode = reason_codes[i];
                    }
                }
            }
        });
        setChooseLesson("选择", "调整课次", "", WLXChooseLessonView.ChooseMode.GRAY);
        setChooseLessonTo("选择", "调后课次", "", WLXChooseLessonView.ChooseMode.GRAY);
    }

    //上面+下面+模式:左边
    public void setChooseLesson(String top, String bottom, String line, WLXChooseLessonView
            .ChooseMode mode) {
        mChooseAdjustLesson.setTop(top);
        mChooseAdjustLesson.setBottom(bottom);
        mChooseAdjustLesson.changeMode(mode);
        mTvCenterAdjustLine.setText(line);
    }

    //上面+下面+模式:右边
    public void setChooseLessonTo(String top, String bottom, String line, WLXChooseLessonView
            .ChooseMode mode) {
        mChooseAdjustLessonTo.setTop(top);
        mChooseAdjustLessonTo.setBottom(bottom);
        mChooseAdjustLessonTo.changeMode(mode);
        mTvCenterAdjustLine.setText(line);
    }

    @OnClick({R.id.iv_back, R.id.tv_save, R.id.choose_adjust_lesson, R.id
            .choose_adjust_lesson_to})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                if (checkIfComplete()) {
                    requestNet2AdjustLseeon();
                }
                break;
            case R.id.choose_adjust_lesson:
                if (adjustTimes.size() == 0) {
                    WLXCustomToast.show("没有课次可调");
                    return;
                }
                WLXWheelViewUtils.showOneWheel(this, adjustTimes, "选择调课课次", 0, new OptionsPickerView
                        .OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        String[] split = adjustTimes.get(options1).split(" ");
                        wlx_schedule wlx_schedule = mWlx_schedules.get(options1);
                        schedule_id = wlx_schedule.getSchedule_id();
                        setChooseLesson(split[0], split[1], "", WLXChooseLessonView.ChooseMode
                                .YELLOWROUND);
                    }
                });
                break;
            case R.id.choose_adjust_lesson_to:
                if (adjustTimes.size() == 0) {
                    WLXCustomToast.show("没有课次可调");
                    return;
                }
                WLXWheelViewUtils.showTwoWheel(this, lowTime, "选择调课课次", 0, 3, new
                        OptionsPickerView.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int option2, int options3) {

                                setChooseLessonTo(WLXWheelViewUtils.getShowTime(option2),
                                        WLXWheelViewUtils
                                                .getTimeString(option2), "调整为", WLXChooseLessonView
                                                .ChooseMode.YELLOWROUND);
                                new_start_date = WLXWheelViewUtils.getOpenTimeString(options1,
                                        option2);
                                new_end_date = WLXWheelViewUtils.getCloseTimeString(options1,
                                        option2);
                            }
                        });
                break;
        }
    }

    //检查是否全部都选择了,并且请求数据已经OK
    private boolean checkIfComplete() {
        if (TextUtils.isEmpty(reasonCode)) {
            WLXCustomToast.show("请选择调课原因");
            return false;
        }
        if (TextUtils.isEmpty(schedule_id) || TextUtils.isEmpty(new_start_date) || TextUtils
                .isEmpty(new_end_date)) {
            WLXCustomToast.show("请选择调课时间");
            return false;
        }
        return true;
    }

    //做网络请求去调整课次
    private void requestNet2AdjustLseeon() {
        WLXHttpRxHelper.getInstance().adjustLesson(WLXConstant.GRADE_ID, schedule_id, reasonCode,
                new_start_date, new_end_date,
                new Subscriber<WLXGetCodeBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        WLXCustomToast.show("网络异常,请检查网络");
                    }

                    @Override
                    public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                        if (wlxGetCodeBean.getCode() == 0) {
                            new AlertView("提示", "调课成功", null, new String[]{"确定"}, null,
                                    WLXClazzAdjustActivity.this,
                                    AlertView.Style.Alert, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int position) {
                                    WLXClazzAdjustActivity.this.finish();
                                }
                            }).show();
                        } else {
                            Toast.makeText(WLXClazzAdjustActivity.this, wlxGetCodeBean.getMsg(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //恢复到初始状态
    private void restoreState() {
        //恢复调课时间
        setChooseLesson("选择", "调整课次", "", WLXChooseLessonView.ChooseMode.GRAY);
        setChooseLessonTo("选择", "调后课次", "", WLXChooseLessonView.ChooseMode.GRAY);
    }


    /**
     * 动态添加内容
     */
    private void initRadioButton() {
        WindowManager manager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        int width = manager.getDefaultDisplay().getWidth();
        // 动态加载radiobutton的时候要用  radioGroup.layoutParams 来实现
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(width / 3 - 65,
                WRAP_CONTENT);
        layoutParams.setMargins(18, 13, 18, 10);
        radioButtons = new RadioButton[titles.length];
        for (int i = 0; i < radioButtons.length; i++) {
            radioButtons[i] = new RadioButton(this);
            radioButtons[i].setText(titles[i]);
            radioButtons[i].setButtonDrawable(null);
            radioButtons[i].setBackgroundResource(R.drawable.selector_feedback);
            radioButtons[i].setTextColor(this.getResources().getColorStateList(R.color
                    .color_feedback_name));
            radioButtons[i].setGravity(Gravity.CENTER);
            radioButtons[i].setTag(i);
            radioButtons[i].setId(i);
            radioButtons[i].setLayoutParams(layoutParams);
            mFlowRadioGroup.addView(radioButtons[i]);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        WLXWheelViewUtils.dismiss();
    }

    @Override
    public void onBackPressed() {
        if (WLXWheelViewUtils.isShowing()) {
            WLXWheelViewUtils.dismiss();
            return;
        }
        super.onBackPressed();
    }
}
